import 'package:flutter/material.dart';

import '../../repository/sjx_api.dart';

class LogOffPage extends StatefulWidget {
  const LogOffPage({super.key});

  @override
  State<LogOffPage> createState() => _LogOffPageState();
}

class _LogOffPageState extends State<LogOffPage> {
  final List<String> _reasons = [
    '不想用了',
    '功能不满足需求',
    '安全性担忧',
    '找到了更好的替代品',
    '使用频率太低',
    '其他原因',
  ];

  final TextEditingController _reasonController = TextEditingController();
  String _selectedReason = '';
  final int _maxLength = 200;
  int _currentLength = 0;

  @override
  void initState() {
    super.initState();
    _reasonController.addListener(_updateLength);
  }

  @override
  void dispose() {
    _reasonController.dispose();
    super.dispose();
  }

  void _updateLength() {
    setState(() {
      _currentLength = _reasonController.text.length;
    });
  }

  void _showConfirmDialog() {
    if (_selectedReason.isEmpty && _reasonController.text.isEmpty) {
      _showMessage('请选择或输入注销原因');
      return;
    }

    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('确认注销'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Text(
                '注销账户后，以下信息将被永久删除且无法恢复：',
                style: TextStyle(fontSize: 14),
              ),
              const SizedBox(height: 12),
              _buildWarningItem('账户所有个人信息'),
              _buildWarningItem('历史记录和数据'),
              _buildWarningItem('已绑定的支付账户'),
              _buildWarningItem('优惠券和积分'),
              const SizedBox(height: 12),
              const Text(
                '请确认是否继续注销？',
                style: TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.bold,
                  color: Colors.red,
                ),
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text('再考虑一下'),
            ),
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
                _performLogOff();
              },
              style: TextButton.styleFrom(
                foregroundColor: Colors.red,
              ),
              child: const Text('确认注销'),
            ),
          ],
        );
      },
    );
  }

  Widget _buildWarningItem(String text) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 2),
      child: Row(
        children: [
          const Icon(
            Icons.warning_amber_rounded,
            size: 16,
            color: Colors.orange,
          ),
          const SizedBox(width: 8),
          Text(
            text,
            style: const TextStyle(fontSize: 13),
          ),
        ],
      ),
    );
  }

  Future<void> _performLogOff() async {
    await SJXApi.instance().feedback('注销-'+this._selectedReason+'-'+_reasonController.text.trim());
    _showSuccessDialog();
  }

  void _showSuccessDialog() {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('注销申请已提交'),
          content: const Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(
                Icons.check_circle,
                color: Colors.green,
                size: 48,
              ),
              SizedBox(height: 16),
              Text(
                '您的账户注销申请已提交，我们将在1-7个工作日内处理完成。处理期间您将无法使用账户功能。',
                textAlign: TextAlign.center,
                style: TextStyle(fontSize: 14),
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
                // 返回首页或登录页
                Navigator.of(context).popUntil((route) => route.isFirst);
              },
              child: const Text('确定'),
            ),
          ],
        );
      },
    );
  }

  void _showMessage(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        duration: const Duration(seconds: 2),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('注销账户'),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => Navigator.of(context).pop(),
        ),
      ),
      backgroundColor: const Color.fromRGBO(244, 247, 250, 1),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 警告提示
            Container(
              width: double.infinity,
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: const Color(0xFFFFF2E8),
                borderRadius: BorderRadius.circular(8),
                border: Border.all(
                  color: const Color(0xFFFFBB96),
                  width: 1,
                ),
              ),
              child: const Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Icon(
                    Icons.warning_amber_rounded,
                    color: Color(0xFFFA541C),
                    size: 20,
                  ),
                  SizedBox(width: 12),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          '重要提示',
                          style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                            color: Color(0xFFFA541C),
                          ),
                        ),
                        SizedBox(height: 4),
                        Text(
                          '账户注销是不可逆的操作，一旦注销，所有数据将被永久删除且无法恢复。请谨慎操作。',
                          style: TextStyle(
                            fontSize: 14,
                            color: Color(0xFFFA541C),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),

            const SizedBox(height: 24),

            // 注销原因选择
            const Text(
              '请选择注销原因（必选）',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w500,
                color: Color(0xFF262626),
              ),
            ),
            const SizedBox(height: 12),

            // 原因选项
            Column(
              children: _reasons.map((reason) {
                return _buildReasonItem(reason);
              }).toList(),
            ),

            const SizedBox(height: 24),

            // 其他原因输入
            const Text(
              '其他原因（选填）',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w500,
                color: Color(0xFF262626),
              ),
            ),
            const SizedBox(height: 12),

            Container(
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(8),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.05),
                    blurRadius: 4,
                    offset: const Offset(0, 2),
                  ),
                ],
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 16),
                    child: TextField(
                      controller: _reasonController,
                      maxLines: 4,
                      maxLength: _maxLength,
                      decoration: const InputDecoration(
                        border: InputBorder.none,
                        hintText: '请详细说明您的注销原因...',
                        hintStyle: TextStyle(
                          color: Color(0xFFBFBFBF),
                          fontSize: 14,
                        ),
                        contentPadding: EdgeInsets.symmetric(vertical: 12),
                      ),
                      style: const TextStyle(
                        fontSize: 14,
                        color: Color(0xFF262626),
                      ),
                    ),
                  ),
                  // 字数统计
                  Padding(
                    padding: const EdgeInsets.fromLTRB(16, 0, 16, 12),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        // Text(
                        //   '$_currentLength/$_maxLength',
                        //   style: TextStyle(
                        //     fontSize: 12,
                        //     color: _currentLength > _maxLength
                        //         ? Colors.red
                        //         : const Color(0xFF8C8C8C),
                        //   ),
                        // ),
                      ],
                    ),
                  ),
                ],
              ),
            ),

            const SizedBox(height: 32),

            // 注销协议
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: const Color(0xFFF6F6F6),
                borderRadius: BorderRadius.circular(6),
              ),
              child: const Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '注销协议',
                    style: TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.bold,
                      color: Color(0xFF262626),
                    ),
                  ),
                  SizedBox(height: 8),
                  Text(
                    '1. 注销后，您的账户信息、个人数据、历史记录等将被永久删除且无法恢复。\n'
                        '2. 注销前请确保已处理完所有未完成的交易和业务。\n'
                        '3. 注销申请提交后，我们将进行审核，审核期间账户将被冻结。\n'
                        '4. 注销成功后，您将无法使用该账户登录和使用相关服务。',
                    style: TextStyle(
                      fontSize: 12,
                      color: Color(0xFF595959),
                      height: 1.5,
                    ),
                  ),
                ],
              ),
            ),

            const SizedBox(height: 40),
          ],
        ),
      ),
      // 底部注销按钮
      bottomNavigationBar: SafeArea(
        child: Container(
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: Colors.white,
            border: Border(
              top: BorderSide(
                color: Colors.grey.shade200,
                width: 1,
              ),
            ),
          ),
          child: SizedBox(
            width: double.infinity,
            height: 44,
            child: ElevatedButton(
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.red,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(22),
                ),
                elevation: 0,
              ),
              onPressed: _showConfirmDialog,
              child: const Text(
                '申请注销',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w500,
                  color: Colors.white,
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildReasonItem(String reason) {
    final bool isSelected = _selectedReason == reason;

    return Container(
      margin: const EdgeInsets.only(bottom: 8),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 4,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: RadioListTile<String>(
        title: Text(
          reason,
          style: const TextStyle(
            fontSize: 14,
            color: Color(0xFF262626),
          ),
        ),
        value: reason,
        groupValue: _selectedReason,
        onChanged: (String? value) {
          setState(() {
            _selectedReason = value ?? '';
          });
        },
        activeColor: Colors.red,
        controlAffinity: ListTileControlAffinity.trailing,
        contentPadding: const EdgeInsets.symmetric(horizontal: 12),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(8),
        ),
        tileColor: isSelected ? const Color(0xFFFFF2F0) : Colors.white,
      ),
    );
  }
}